package com.orangelife.mobile.surrounding.activity;

import android.content.Intent;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.common.jump.CommonJumper;
import com.common.sp.UserSp;
import com.curry.android.net.NetworkUtil;
import com.curry.android.util.DecimalUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.ImageDownloader;
import com.curry.android.util.ImageDownloader.ImageSize;
import com.curry.android.util.JSONHelper;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.app.application.CurryApplication;
import com.orangelife.mobile.app.application.ExitApplication;
import com.orangelife.mobile.buyFresh.adapter.BuyFreshGridViewAdapter;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.confirmOrder.activity.ShoppingConfirmOrderActivity;
import com.orangelife.mobile.confirmOrder.activity.GoodsRentConfirmOrderActivity;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.goodsrent.dao.GoodsDao;
import com.orangelife.mobile.goodsrent.entity.GoodsInfo;
import com.orangelife.mobile.pay.biz.PaymentModule;
import com.orangelife.mobile.shoppingcart.biz.ShoppingCartBiz;
import com.orangelife.mobile.util.ToastHelper;
import com.orangelife.mobile.widget.ScrollGridView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 选择规格界面，包括“加入购物车”和“下单”
 * <p/>
 * Create by cfr on .Modify by wgf on 160224.
 *
 * @author cfr
 * @since v2.0
 */
public class SelectedStandardActivity extends OrangeLifeBaseActivity {

    private View mMenuView;
    /**
     * 商品图片
     */
    private ImageView ivPhoto;
    /**
     * 现价
     */
    private TextView tvPriceDiscount;
    /**
     * 原价
     */
    private TextView tvPrice;
    /**
     * 选重
     */
    private TextView tvWeight;
    /**
     * gridview
     */
    private ScrollGridView gvWeight;
    /**
     * 减号
     */
    private ImageButton ibMinus;
    /**
     * 加号
     */
    private ImageButton ibPlus;
    /**
     * 数量
     */
    private TextView tvCount;
    /**
     * 购买按钮
     */
    private Button btnBuy;
    /**
     * 加入购物车
     */
    private Button btnAddShoppingCard;
    /**
     * 关闭
     */
    private ImageButton ibClose;
    /**
     * 加入购物车按钮和立即购买按钮之间的空格
     */
    private View viewShoppingBuy;
    /**
     * 选择数量或者选择天数
     */
    private TextView tvSelectCount;
    private  String productID;

    private List<Map<String, Object>> listSpecification;
    private Map<String, Object> mapSpe;

    private GoodsInfo goodsInfo;
    /**
     * 商品数量
     */
    private String count;
    /**
     * 上次的选择
     */
    private int positionLast = 0;

    /**
     * 判断是从哪里发过来的，1表示的是从选择规格点击过来的，2表示从加入购物车点击过来的，3表示从立即购买点击过来
     */
    private int flag;

    private boolean isRent;

    private RelativeLayout Rl_layout;
    private LinearLayout pop_layout;
    private ImageDownloader image = ImageDownloader.getImageDownloader();
    private String totalPrice;
    //	private Map<String,List<String>> map;
    private List<HashMap<String, Object>> listMerchant;
    private List<String> listProducts;
    private boolean isTehui = false;//是否是特惠跳转过来
    private int tehuiStatus = 0;//是否显示购物车
    private String activityGoodsID;
    private static final String IS_TEHUI = "isTehui";
    private int limiteNum;//限购数量
    private Intent result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_circumtesco_selectedstandard);
        getWindow().setLayout(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT);
        initView();
        findView();
    }

    private void initView() {
        Rl_layout = (RelativeLayout) findViewById(R.id.rl_layout);
        pop_layout = (LinearLayout) findViewById(R.id.pop_layout);
        ivPhoto = (ImageView) findViewById(R.id.ivPhoto);
        tvPriceDiscount = (TextView) findViewById(R.id.tvPriceDiscount);
        tvPrice = (TextView) findViewById(R.id.tvPrice);
        tvWeight = (TextView) findViewById(R.id.tvWeight);
        gvWeight = (ScrollGridView) findViewById(R.id.gvSpecification);
        ibClose = (ImageButton) findViewById(R.id.ibClose);
        ibMinus = (ImageButton) findViewById(R.id.ibDelete);
        ibPlus = (ImageButton) findViewById(R.id.ibPlus);
        tvCount = (TextView) findViewById(R.id.tvCount);
        btnBuy = (Button) findViewById(R.id.btnBuy);
        btnAddShoppingCard = (Button) findViewById(R.id.btnAddShoppingCard);
        viewShoppingBuy = findViewById(R.id.viewShoppingBuy);
        tvSelectCount = (TextView) findViewById(R.id.tvSelectCount);
    }

    private void findView() {
        result = new Intent();
        Intent intent = getIntent();
        flag = intent.getIntExtra("flag", 0);
        positionLast = intent.getIntExtra("position", 0);
        isRent = intent.getBooleanExtra("isRent", false);
        isTehui = intent.getBooleanExtra(IS_TEHUI, false);
        if (isTehui) {//如果是特惠跳转过来，获取特惠活动的商品id
            activityGoodsID = intent.getStringExtra("activityGoodsID");
            tehuiStatus = intent.getIntExtra("tehuiStatus", tehuiStatus);
            limiteNum = intent.getIntExtra("limiteNum", 1);
        }
        if (isRent) {
            goodsInfo = intent.getParcelableExtra("specification");
            tvSelectCount.setText("选择天数");
        } else {
            mapSpe = (Map<String, Object>) intent
                    .getSerializableExtra("specification");
        }
        switch (flag) {
            case 1:
                if (tehuiStatus == 1) {//活动中的特惠商品不显示购物车
                    btnBuy.setVisibility(View.VISIBLE);
                    btnAddShoppingCard.setVisibility(View.GONE);
                    viewShoppingBuy.setVisibility(View.GONE);
                }
                break;
            case 2:
                btnAddShoppingCard.setVisibility(View.VISIBLE);
                btnBuy.setVisibility(View.GONE);
                viewShoppingBuy.setVisibility(View.GONE);
                break;
            case 3:
                btnBuy.setVisibility(View.VISIBLE);
                btnAddShoppingCard.setVisibility(View.GONE);
                viewShoppingBuy.setVisibility(View.GONE);
                break;
            default:
                break;
        }
        // 取消按钮
        ibClose.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // 销毁弹出框
                setResult(RESULT_OK, result);
                finish();
            }
        });
        tvCount.setText(1 + "");
        if (isRent) {
            listSpecification = new ArrayList<>();
            Map<String, Object> map = new HashMap<>();
            map.put("price", goodsInfo.getPrice());
            listSpecification.add(map);
        } else {
            listSpecification = (List<Map<String, Object>>) mapSpe.get("products");
        }
        setGridViewText(positionLast);
        gvWeight.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                TextView tvSelectWeight = (TextView) view
                        .findViewById(R.id.tvWeight);
                setGridViewText(position);
                positionLast = position;
                result.putExtra("position", positionLast);
            }
        });

        ibMinus.setOnClickListener(itemsOnClick);
        ibPlus.setOnClickListener(itemsOnClick);
        btnBuy.setOnClickListener(itemsOnClick);
        btnAddShoppingCard.setOnClickListener(itemsOnClick);

        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0xb0000000);

        // mMenuView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框
        Rl_layout.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                int height = pop_layout.getTop();
                int y = (int) event.getY();
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (y < height) {
                        setResult(RESULT_OK, result);
                        finish();
                    }
                }
                return true;
            }
        });
        ToastHelper.getInstance().init(this);
    }

    private void setGridViewText(int positionLast) {
        BuyFreshGridViewAdapter adapter;
        if (isRent) {
            adapter = new BuyFreshGridViewAdapter(this,
                    listSpecification, positionLast, true);
            image.download(goodsInfo.getGoodsLogo(), ivPhoto,
                    ImageSize.IMAGE_SIZE_EXTRA_SMALL_RECTANGLE_JPG);

            tvPrice.setVisibility(View.VISIBLE);
            tvPriceDiscount.setText(Constant.RMB_FLAG
                    + goodsInfo.getPrice());
            tvPrice.setText(Constant.RMB_FLAG
                    + goodsInfo.getPrice());
            tvPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);

            tvWeight.setText("已选：“" + goodsInfo.getPrice() + "元/天”");
        } else {
            adapter = new BuyFreshGridViewAdapter(this,
                    listSpecification, positionLast, false);
            image.download(mapSpe.get("goodsLogo").toString(), ivPhoto,
                    ImageSize.IMAGE_SIZE_EXTRA_SMALL_RECTANGLE_JPG);
            if (getIntent().getBooleanExtra("score", false)) {
                tvPrice.setVisibility(View.GONE);
                tvPriceDiscount.setText(listSpecification.get(positionLast).get("score").toString() + "积分");
            } else {
                tvPrice.setVisibility(View.VISIBLE);
                tvPriceDiscount.setText(Constant.RMB_FLAG
                        + listSpecification.get(positionLast).get("price").toString());
                tvPrice.setText(Constant.RMB_FLAG
                        + listSpecification.get(positionLast).get("mkPrice").toString());
                tvPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            }
            tvWeight.setText("已选：“" + listSpecification.get(positionLast).get("pdtDesc").toString() + "”");
        }
        gvWeight.setAdapter(adapter);


    }

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            DialogHelper.closeDialog(dialog);
            switch (msg.what) {
                case 0:
                    String errCode = JSONHelper.jsonToMap(msg.obj.toString())
                            .get("errCode").toString();
                    if (errCode.equals("0")) {
                        DialogHelper.closeDialog(dialog);

                        ToastHelper.getInstance()._toast(
                                getResources().getString(
                                        R.string.submit_success));
                    } else {
                        DialogHelper.closeDialog(dialog);
                        ToastHelper.getInstance()._toast(
                                getResources().getString(
                                        R.string.validation_fail_info));
                    }
                    break;
                default:
                    break;
            }
        }
    };

    private OnClickListener itemsOnClick = new OnClickListener() {

        @Override
        public void onClick(View v) {
            String price = String.valueOf(listSpecification.get(positionLast).get("price"));
            String day = String.valueOf(tvCount.getText().toString());
            switch (v.getId()) {
                case R.id.ibDelete:
                    count = tvCount.getText().toString();
                    if (count.compareTo("1") > 0) {
                        count = DecimalUtil.subtract(count, "1");
                        tvCount.setText(count + "");
                    }
                    count = tvCount.getText().toString();
                    if (count.compareTo("2") < 0) {
                        ibMinus.setBackgroundResource(R.drawable.count_delete_gray);
                    }

                    break;
                case R.id.ibPlus:
                    count = tvCount.getText().toString();
                    if (isRent) {
                        String mastDay = goodsInfo.getPdtDesc();
                        if (DecimalUtil.subtract(count, mastDay).compareTo("0") > 0) {
                            ToastHelper.getInstance()._toast("超过可租借天数");
                            return;
                        }
                    }
                    if (tehuiStatus == 1) {
                        int max = Integer.parseInt(count);
                        if (max >= limiteNum) {
                            ToastHelper.getInstance().displayToastWithQuickClose("已达到购买上限");
                            return;
                        }
                    }
                    count = DecimalUtil.add(count, "1");
                    tvCount.setText(count + "");
                    count = tvCount.getText().toString();
                    if (count.compareTo("1") > 0) {
                        ibMinus.setBackgroundResource(R.drawable.count_delete);
                    }


                    break;
                case R.id.btnBuy:
                    if (TextUtils.isEmpty(UserSp.getAccessToken())) {
                        ToastHelper.getInstance()._toast("请先登录");
                        CommonJumper.jumpToLogin(SelectedStandardActivity.this);
                    } else {
                        ((CurryApplication) SelectedStandardActivity.this.getApplicationContext()).setShopping(false);
                        ExitApplication.getInstance().addPaidActivity(SelectedStandardActivity.this);
                        if (isRent) {
                            goodsInfo.setDay(tvCount.getText().toString());
                            goodsInfo.setUnitPrice(DecimalUtil.multiply(price, day));
                            Intent intent = new Intent(SelectedStandardActivity.this, GoodsRentConfirmOrderActivity.class);
                            intent.putExtra(GoodsRentConfirmOrderActivity.GOODS_INFO, goodsInfo);
                            startActivity(intent);
                        } else {
                            instanceConfirm();
                        }
                    }

                    break;
                case R.id.btnAddShoppingCard:
                    //加入购物车
                    if (isRent) {
                        //租借的加入购物车
                        goodsInfo.setUnitPrice(DecimalUtil.multiply(price, day));
                        goodsInfo.setDay(tvCount.getText().toString());
                        if (GoodsDao.getInstance().isExistGood(goodsInfo.getrGoodID())) {
                            ToastHelper.getInstance()._toast("购物车已存在此商品");
                        } else {
                            GoodsDao.getInstance().insertUserInfo(goodsInfo);
                        }
                    } else {
                        String productID = listSpecification.get(positionLast).get("productID").toString();
                        if (ShoppingCartBiz.isProductExist(productID)) {
                            ToastHelper.getInstance()._toast("购物车已存在此商品");
                        } else {
                            String num = tvCount.getText().toString();
                            ShoppingCartBiz.saveGoodNum(productID, num);
                            ToastHelper.getInstance()._toast("商品已加入购物车");
                        }
                    }
                    finish();
                    break;

                default:
                    break;
            }

        }

    };

    private void instanceConfirm() {
        setParams();
//		map.put(ShoppingConfirmOrderActivity.GOODS_TOTAL_PRICE,totalPrice);
        Bundle bundle = new Bundle();
//		bundle.putSerializable("productIDs", (Serializable) listProducts);
        totalPrice = DecimalUtil.multiply(tvCount.getText().toString(), tvPriceDiscount.getText().toString().replace(Constant.RMB_FLAG, ""));
        bundle.putSerializable(ShoppingConfirmOrderActivity.SHOPPING_CART_LIST, (Serializable) listMerchant);
        bundle.putSerializable(ShoppingConfirmOrderActivity.PRODUCT_LIST_IDS, (Serializable) listProducts);
        bundle.putString(ShoppingConfirmOrderActivity.GOODS_PRICES, totalPrice);
        bundle.putString(ShoppingConfirmOrderActivity.TYPE, PaymentModule.mode[1]);
        bundle.putBoolean(IS_TEHUI, isTehui);//传入是否是特惠
        bundle.putString("productID",productID);
        if (isTehui) {
            bundle.putInt("tehuiStatus", tehuiStatus);
            bundle.putString("activityGoodsID", activityGoodsID);
        }
        Intent intent = new Intent();
        intent.putExtras(bundle);
        intent.setClass(SelectedStandardActivity.this, ShoppingConfirmOrderActivity.class);
        startActivity(intent);
        finish();
    }

    private void setParams() {
        listMerchant = new ArrayList<>();
        HashMap<String, Object> mapMerchantInfo = new HashMap<>();
         productID = listSpecification.get(positionLast).get("productID").toString();
        listProducts = new ArrayList<>();
        List<String> productNumbers = new ArrayList<>();
        List<String> sellPloys = new ArrayList<>();
        listProducts.add(productID);
        productNumbers.add(tvCount.getText().toString());
        sellPloys.add(mapSpe.get("sellPloyID").toString());
        mapMerchantInfo.put(ShoppingConfirmOrderActivity.PRODUCT_IDS, listProducts);
        mapMerchantInfo.put(ShoppingConfirmOrderActivity.PRODUCT_NUMBER, productNumbers);
        mapMerchantInfo.put(ShoppingConfirmOrderActivity.SELLPLOY_ID, sellPloys);
        mapMerchantInfo.put(ShoppingConfirmOrderActivity.MER_ID, mapSpe.get("merID").toString());
        listMerchant.add(mapMerchantInfo);
    }

    /**
     * 是否联网
     *
     * @return true-联网，false-断网；
     */
    protected boolean isConnected() {
        if (!NetworkUtil.isConnectedNet(this)) {
            Toast.makeText(this,
                    getResources().getString(R.string.net_disconnected),
                    Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

}
